<?php
namespace App\Repos;
use App\Models\User;
use App\Models\UserCoordinate;
use App\Models\Order;
use App\Models\UserMoneyLog;
use App\Models\UserSetting;
use App\Models\UserCoupon;
use App\Models\UserPoint;
use App\Models\Intend;
use App\Models\InvitePoint;
use App\Models\Invite;
use DB,Log;
use App\Services\RedisService;

class UserRepo
{
	public static function  getList($where=[],$num=10)
	{	   
	  	$query = User::query();
	  	if(array_get($where,'keyword')) {
	  		$query->where('name','like','%'.$where['keyword'].'%');
	  		$query->orWhere('phone','like','%'.$where['keyword'].'%');
	  	}
	  	$list = $query->paginate($num); 
	  	return $list;     
	}

	

	public static function create($data)
	{
		
		
		$data['token_date'] = date('Y-m-d H:i:s',strtotime("+1 week"));
		
		$flag = '';
		DB::beginTransaction();
		try {
			$user = User::where(['unionid'=>$data['unionid']])->first();
			if($user) {
				$arr = array_except($data,['remember_token','unionid']);
				self::update(['unionid'=>$data['unionid']],$arr);
			} else {
				$user = User::create($data);
			}			
			
			$us = UserSetting::where(['user_id'=>$user->id])->first();
			if(!$us) {
				 $us['user_id'] = $user->id;
				 UserSetting::create($us);

			}
			DB::commit();	
			// 根据id建缓存
			RedisService::addUser('id:'.$user->id,   $user->toJson());

			// 根据token建缓存
			RedisService::addUser('token:'.$user->remember_token,$user->toJson());
			
			
		} catch (\Exception $e) {

			Log::info('注册用户失败:'.$e->getMessage());
			DB::rollBack();
			return false;
		}
		
		return $user;
	}

	public static function find($where=[])
	{
		return User::where($where)->with('coord')->first();
	}

	public static function getUserInfo($where=[])
	{
		$data = self::find($where);
		if(object_get($data,'idcard')) {
			$data->idcard = substr_replace($data->idcard, '******', -6,6);	
		}
		if(object_get($data,'mobile')) {
			$data->mobile = substr_replace($data->mobile,'****', 4,4);	
		}
		if(object_get($data,'wechat')) {
			$data->wechat = substr_replace($data->wechat,'****', 4,4);
		}
		if(object_get($data,'email')) {
			$data->email  = substr_replace($data->email,'****', 4,4);
		}
		return $data;
	}

	

	

	public static function getUserMoneyLog($where=[],$num=10)
	{
		
		$list = UserMoneyLog::where($where)
							->paginate($num);
							
		return $list;					
	}

	public static function getUserCoupon($user_id,$num=10)
	{
		$where['user_id'] = $user_id;
		//$where['type'] =1;
		$list = UserCoupon::with(['user'])
							->where($where)
							->paginate($num);
		return $list;
	}

	public static function  getOrders($user_id,$num=10)
	{	   
	  	$list = Order::where(['user_id'=>$user_id])->paginate($num); 
	  	return $list;     
	}


	public static function update($where,$data)
	{
		$rs['status'] = false;
		$flag = User::where($where)->update($data);

		$user = User::where($where)->first();
		// 根据id更新缓存
		RedisService::addUser('id:'.$user->id,   $user->toJson());

		// 根据token更新缓存
		RedisService::addUser('token:'.$user->remember_token,$user->toJson());

		if($flag) {
			$rs['status'] = true;
			return $rs;
		}
		return $rs;
	}

	public static function changeStatus($id,$data)
	{
		$updateData['status'] = $data['status'];
        self::update(['id'=>$id],$updateData);
		$flag = AdminHandlerLogRepo::create('User',$id,$data);
		return true;
	}


	

	public static function count()
	{
		$num = User::count();
		return $num;
	}

	// 查询目标对象 如果map有值表明是首页的搜索，否则就从理想对象中查
	public static function queryIntendUser($user_id,$map=[])
	{
		$intend = [];
		if(empty($map)) {
			$intend = Intend::where(['user_id'=>$user_id])
								->first();
			if($intend) {
				$intend = $intend->toArray();
			}					
								
		} else {
			$intend = $map;
		}
		
		//排除掉邀约成功的
		$iMap['from_user_id'] = $user_id;
		$iMap['status'] = 100;
		$except_userids = Invite::where($iMap)->pluck('to_user_id');

		$query  = DB::table('users as u')
					->select(['u.id','u.sex','u.face_score','avatar','u.salary_rank','u.xueli_rank','wx_avatar','avatar','coord.coord','us.open_info','u.birthday']);
		 $query->join('user_coordinates as coord','u.id','=','coord.user_id');
		    $query->join('user_settings as us','u.id','=','us.user_id');	
		$query->where('us.open_info','!=','1'); 
		
		if($intend) {		

			$radioItem = array_only($intend,['is_smoke','is_married','is_ill','is_havebaby']);

			if(array_get($intend,'sex')) {
				$query->where('u.sex',$intend['sex']);	
			}

			if(array_get($intend,'is_wantbaby')) {
				$query->where('u.is_wantbaby',$intend['is_wantbaby']);
			}



			
			

			foreach ($radioItem as $k => $v) {
				if($v==1) {
					$query->where('u.'.$k,2);
				}
			}
			//dd($query->get(),$intend['height']);
			if(array_get($intend,'height') && strpos($intend['height'],',') ) {				
				$height = explode(',', $intend['height']);
				$query->whereBetween('u.height',$height);
			}

			if(array_get($intend,'age') && strpos($intend['age'],',') ) {
				$age = explode(',', $intend['age']);
				//dd($age);
				$query->whereYear('birthday','>=',$age[0]);
				$query->whereYear('birthday','<=',$age[1]);
				
			}

			

			if(array_get($intend,'xueli_rank')) {
				$query->where('u.xueli_rank','>=',(int)$intend['xueli_rank']);
			}

			if(array_get($intend,'salary_rank')) {
				$query->where('u.salary_rank','>=',(int)$intend['salary_rank']);
			}

			

			if(array_get($intend,'face_score')) {
				$query->where('face_score','>=',(int)$intend['face_score']);
			}
		}
		$query->whereNotIn('u.id',$except_userids);   
		   
		return $query->get();
	}

	/**
	 * 发起邀约使用积分，先用优惠券的，然后用充值的。
	 */
	public static function usePoint($data)
	{
		$rs['status'] = false;
		$user = User::select(['point','coupon_point','id'])
						->where(['id'=>$data['user_id']])
						->first();
		$coupon_point = (int)$user->coupon_point;
		$point        = (int)$user->point;						
		if(($coupon_point+$point)<$data['point']) {
			$rs['msg'] = '积分不足，请先充值';
			return $rs;
		}
		if($coupon_point>$data['point']) {

			$user->coupon_point -= $data['point'];
			$user->save();
			$rs['status'] = true;
			$rs['data']['coupon_point'] = $data['point'];
			$uc['user_id'] = $user->id;
			$uc['coupon_point'] = $data['point'];
			$uc['type'] = 2;
			$uc['remark'] = '邀约用户消费代金券积分:'.$data['point'];
			UserCoupon::create($uc);
			return $rs;
		}

		//代金券不够的话 还要从积分里扣
		if($coupon_point<$data['point']) {
			$user->coupon_point = 0;
			$user->point = $point-($data['point']-$coupon_point);
			$user->save();
			$rs['data']['coupon_point'] = $coupon_point;
			$rs['data']['point'] = $data['point']-$coupon_point;
			$rs['status'] = true;

			$up['user_id'] = $user->id;
			$up['point']   = $data['point']-$coupon_point;
			$up['type']    = 2;
			$up['remark']  = '邀约用户消费积分:'.$data['point']-$coupon_point;
			UserPoint::create($up);

			$uc['user_id']      = $user->id;
			$uc['coupon_point'] = $coupon_point;
			$uc['type'] = 2;
			$uc['remark'] = '邀约用户消费代金券积分:'.$coupon_point;
			UserCoupon::create($uc);
			return $rs;
		}

		
		return $rs;
	}

	public static function createTest($data)
	{
		
		$data['token_date'] = date('Y-m-d H:i:s',strtotime("+1 week"));
		
		$flag = '';
		DB::beginTransaction();
		try {
			$user = User::updateOrCreate(['nickname'=>$data['nickname']],$data);
			$coor['user_id']   = $user->id;
			$coor['coord'] = array_get($data,'coord');
			
			//UserCoordinate::create($coor);

			
			
			$us = UserSetting::where(['user_id'=>$user->id])->first();
			if(!$us) {
				 $us['user_id'] = $user->id;
				 UserSetting::create($us);

			}
			DB::commit();	
			// 根据id建缓存
			RedisService::addUser($user->id,   $user->toJson());

			// 根据token建缓存
			RedisService::addUser($data['remember_token'],$user->toJson());
			
			
		} catch (\Exception $e) {

			Log::info('注册用户失败:'.$e->getMessage());
			DB::rollBack();
			return false;
		}
		
		return $user;
	}

	/**
	 * 积分充值
	 */
	public static function rechargePoint($user_id,$data)
	{
		DB::beginTransaction();
        try {
            
            // 用户加积分
            $user = User::find($user_id);
            $user->point += $data['point'];
            $user->save();
           
            // 保存充值记录
            $up['user_id']      = $user_id;
            $up['product_id']   = array_get($data,'product_id');
            $up['point'] = $data['point'];
            $up['type']  = 1;
            $flag = UserPoint::create($up);
            DB::commit();
            $rs['status'] = true;
            return $rs;
        } catch (\Exception $e) {
            $rs['msg'] = $e->getMessage();           
            DB::rollBack();
            return $rs;
        }
        

        return $rs;
	} 

	

	
	
	

	
	
	
}